import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
const Login = () => import('@/views/login')
const Layout = () => import('@/views/layout')
const NotFound = () => import('@/views/404')
const Home = () => import('@/views/layout/Home')
const QA = () => import('@/views/layout/QA')
const Video = () => import('@/views/layout/Video')
const User = () => import('@/views/layout/User')
const Edit = () => import('@/views/layout/User/edit')
const Search = () => import('@/views/layout/Search')
const Result = () => import('@/views/layout/Search/Result')
const Article = () => import('@/views/article')
const Chat = () => import('@/views/layout/User/chat')

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '',
        component: Home,
        meta: {
          isKeepAlive: true
        }
      },
      {
        path: '/qa',
        component: QA
      },
      {
        path: '/video',
        component: Video
      },
      {
        path: '/user',
        component: User
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/search/result',
    component: Result
  },
  {
    path: '/article/:id',
    component: Article
  },
  {
    path: '*',
    component: NotFound
  },
  {
    path: '/user/edit',
    component: Edit
  },
  {
    path: '/user/chat',
    component: Chat
  }
]

const router = new VueRouter({
  routes
})

// const loginUrls = ['/user', '/edit', '/chat']
// router.beforeEach((to, from, next) => {
//   const token = store.state.user.token.token
//   if (token) {
//     next()
//     return
//   }
//   if (loginUrls.includes(to.path)) {
//     router.push({
//       path: '/login',
//       query: {
//         back: to.path
//       }
//     })
//   } else {
//     next()
//   }
// })
const loginUrls = ['/user', '/user/chat', '/user/edit']
router.beforeEach((to, from, next) => {
  const token = store.state.user.token.token
  if (token) {
    return next()
  }
  if (loginUrls.includes(to.path)) {
    router.push({
      path: '/login',
      query: {
        back: to.path
      }
    })
  } else {
    next()
  }
})

export default router
